var express = require('express');
var router = express.Router();
var {Mvs} = require("../utils/model")

//get请求
//  /表示路由地址
//  req 请求信息
//  res 响应信息
// next下一个中间键
// res.render 渲染模板
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { 
    title: '电影评论管理系统' ,
    username:req.session.username,
    logintime:req.session.logintime
  
  });
});

//登录
router.get("/login",(req,res)=>{
  var username = req.query.username ;
  res.render("login",{username})
})

//注册
router.get("/register",(req,res)=>{
res.render("register");
})

//退出登录
router.get("/logout",(req,res)=>{
  req.session.destroy(()=>{
     res.redirect("/")
  })
})

//修改密码
router.get("/changepass",(req,res)=>{
  if(req.session.username){
    res.render("changepass",{
      username:req.session.username
    })

  }else{
    res.send("<script>alert('session已经过期无效，请重新登录');location.href='/login'</script>")
    
  }
  
})


//电影列表
router.get("/movie",(req,res)=>{
  if(req.session.username){
    var query = req.query;
    var keyword = query.keyword;
    var sortObj = {
      _id:1
    }
    console.log(query);
    var obj = {};
    if(keyword){
      obj={
        $or:[
          {title:new RegExp(keyword)},
          {year:new RegExp(keyword)},
          {genres:new RegExp(keyword)},
          {'rating.average':new RegExp(keyword)},
          {'directors.name':new RegExp(keyword)},

        ]
      }
    }else{
      sortObj = {...query,...sortObj} // 对象合并 ... 展开运算符 
    }
    
    Mvs.find(obj,{
      _id:0
    }).sort(sortObj)
    .then(result=>{

        res.render("movie",{
          result,
          username:req.session.username
        })
    })
  }else{
    res.send("<script>alert('Session已经过期无效,请重新登录');location.href='/login'</script>")
  }
 
})



module.exports = router;
